package ilender.dispatching;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.ibatis.session.*;

import lombok.*;

import ilender.mappers.*;
import ilender.models.*;
import ilender.util.*;

/**
 * A servlet for serving images.
 */
public class ImagesServlet extends HttpServlet{

	/**
	 * Serve an image
	 *
	 * @param request The HTTP request object.
	 * @param response The HTTP response object.
	 */
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		long imageId=Long.parseLong(request.getParameter("image_id"));
		Exception exp=null;
		try(SqlSession session=MyBatisTools.openSession()){
			MImage image=session.getMapper(ImagesMapper.class).fetchImage(imageId);
			if(null!=image){
				response.setContentType("image/png");
				try(OutputStream out=response.getOutputStream()){
					out.write(image.getBinary_data());
					return;
				}
			}
		}catch(Exception e){}
		try(PrintWriter out=response.getWriter()){
			out.printf("Unable to fetch image #%s\n",imageId);
		}
	}
}
